<?php
/**
 * http.php
 * 文件描述
 * Created on 2018/6/17 15:33
 * Create by xuanqiang
 */

class Ws {
    const HOST = "0.0.0.0";
    const PORT = 8811;

    public $http = null;
    public function __construct()
    {
        $this->ws = new swoole_websocket_server(self::HOST, self::PORT);
        $this->ws->set([
            'enable_static_handler' => true,
            'document_root' => "/var/www/html/develop/swoole_live/public/static",
            'worker_num' => 4,
            'task_worker_num' => 4
        ]);
        $this->ws->on("open",[$this, 'onOpen']);
        $this->ws->on("message",[$this, 'onMessage']);
        $this->ws->on("workerstart",[$this,'onWorkerStart']);
        $this->ws->on("request",[$this,'onRequest']);
        $this->ws->on("task",[$this,'onTask']);
        $this->ws->on("finish",[$this,"onFinish"]);
        $this->ws->on("close",[$this,'onClose']);

        $this->ws->start();
    }
    public function onOpen($ws, $request){
        var_dump($request->fd);
    }

    /**
     *监听ws消息事件
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws, $frame) {
        echo "receive from {$frame->fd}:{$frame->data}".date("Y-m-d H:i:s");
    }


    /**
     * @param $server
     * @param $worker_id
     */
    public function onWorkerStart($server, $worker_id){
        // 定义应用目录
        define('APP_PATH', __DIR__ . '/../application/');
        // 加载基础文件
        //require __DIR__ . '/../thinkphp/base.php';
        require __DIR__ . '/../thinkphp/start.php';
    }

    /**
     * @param $request
     * @param $response
     */
    public function onRequest($request, $response){
        $_SERVER = [];
        if(isset($request->server)) {
            foreach ($request->server as $k => $v) {
                $_SERVER[strtoupper($k)] = $v;
            }
        }
        if(isset($request->header)) {
            foreach ($request->header as $k => $v) {
                $_SERVER[strtoupper($k)] = $v;
            }
        }
        $_GET = [];
        if(isset($request->get)) {
            foreach ($request->get as $k => $v) {
                $_GET[$k] = $v;
            }
        }
        $_POST = [];
        if(isset($request->post)) {
            foreach ($request->post as $k => $v) {
                $_POST[$k] = $v;
            }
        }
        //异步task任务
        $_POST['http_server'] =  $this->ws;

        ob_start(); //用来打开输出缓冲
        // 执行应用并响应
        try{
            think\Container::get('app', [ __DIR__ . '/../application/' ])
                ->run()
                ->send();
        }catch (\Exception $e){
            echo $e->getMessage();
        }
        $res = ob_get_contents();
        ob_end_clean();

        $response->end($res);
    }


    public function onTask($ws, $taskId, $workerId, $data){
        //分发task任务机制，让不同的任务，走不同的逻辑
        $obj = new app\common\lib\task\Task;
        $method = $data['method'];
        $flag = $obj->$method($data['data']);
        //异步发送短信验证码
        return "flag";
    }
    /**
     *当worker进程投递的任务在task_worker中完成时，task进程会通过
     * swoole_server->finish()方法将任务处理的结果发送给worker进程。
     * @param $ws
     * @param $taskId
     * @param $data  $data是任务处理的结果内容
     */
    public function onFinish($ws, $taskId, $data){
        echo "taskId:{$taskId}\n";
        echo "finish-data-success:{$data}\n";
    }
    /**
     * @title onClose
     * @description 监听关闭事件
     * @param $http
     * @param $fd
     */
    public function onClose($http, $fd) {
        echo "close clientId:".$fd;
    }
}

new Ws(); //实例化对象